<template>
  <div class="form-setting-group form-default-value-setting">
    <h4 class="form-item-title">
      {{$t('common.base.defaultValue')}}
      <el-tooltip v-show="showTip" :content="tooltipContent" placement="top">
        <i class="iconfont icon-question"></i>
      </el-tooltip>
    </h4>
    <div class="form-item-box">
      <!-- 后备插槽(默认渲染) -->
      <slot>
        <!-- <div class="select-language-wrap"> -->
          <!-- <input :type="type" :placeholder="$t('common.placeholder.inputSomething', {data1:$t('common.base.defaultValue')})" v-model="field.defaultValue" @input="handleInput" /> -->
          <!-- 选择语言 -->
          <!-- <base-select-language 
            :field="field"
            :defaultOption="{
              formType:'text',
            }"
            defaultFormType="text"
            :defaultValue="field.defaultValue"
            :defaultValueLanguage="field.defaultValueLanguage || {}"
            @save="save"
          >
          </base-select-language>
        </div>
        
        <el-checkbox v-model="defaultValueConfig.isNotModify" @change="update(defaultValueConfig, 'defaultValueConfig', true)" :true-label="1" :false-label="0" :disabled="modifyDefaultValueDisabled">{{$t('common.base.tip.notAllowEdit')}}</el-checkbox> -->

                <!-- start 来源 -->
        <el-select
          class="data-source-type"
          v-if="showDataSource"
          :value="dataSourceType"
          @change="updateDataSourceType"
          :disabled="field.id && field.isMulti"
        >
          <el-option
            v-for="item in dataSourceTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <!-- start 来源 -->

        <!-- start 自定义 -->
        <template v-if="!dataSourceType">
          <div class="default-value__input">
            <el-input
              :type="type"
              :placeholder="$t('common.placeholder.inputDefault')"
              v-model="field.defaultValue"
              @input="handleInput"
            />
            <base-select-language 
              :field="field"
              :defaultOption="{
                formType:'text',
              }"
              defaultFormType="text"
              :defaultValue="field.defaultValue"
              :defaultValueLanguage="field.defaultValueLanguage || {}"
              @save="save"
            >
          </base-select-language>
          </div>
          <el-checkbox
            v-model="defaultValueConfig.isNotModify"
            @change="update(defaultValueConfig, 'defaultValueConfig', true)"
            :true-label="1"
            :false-label="0"
            :disabled="modifyDefaultValueDisabled"
          >
            {{ $t('common.base.tip.notAllowEdit') }}
          </el-checkbox>
        </template>
        <!-- end 自定义 -->

        <!-- start 代码块 -->
        <el-select
          v-model="relatedCodeTemplate.aliasPath"
          @change="updateRelatedCode"
          placeholder="请选择"
          class="form-code-setting"
          popper-class="form-code-setting__popover"
          :popper-append-to-body="false"
          v-else-if="dataSourceType == 3">
          <el-option
            v-for="item in codeOptions"
            :key="item.aliasId"
            :label="item.aliasName"
            :value="item.aliasPath">
          </el-option>
        </el-select>
        <!-- end 数据联动 -->
      </slot>
    </div>
  </div>
</template>

<script>
/* config */
import * as config from '@src/component/form/config';
/* props */
import { settingProps } from '@src/component/form/components/props';
import { FORM_FIELD_TEXT_MAX_LENGTH } from '@src/model/const/Number.ts';
import { validateCurrencyNumber } from '@src/util/currency';
import { isInSubForm } from '@src/component/form/util/index';

import { isMultiLangModules } from '@src/component/util/multiLang/index';
import { getOpenMultiLanguage } from '@hooks/useFormMultiLanguage'

import locales, { t } from '@src/locales'
import { cloneDeep } from 'lodash'

export default {
  name: 'form-default-value-setting',
  props: {
    ...settingProps,
    type: {
      type: String,
      default: 'text'
    },
    showTip: {
      type: Boolean,
      default: true
    },
    tooltipContent: {
      type: String,
      default: t('common.base.tip.showInInputAfterSet')
    },
    maxLength: {
      type: Number,
      default: FORM_FIELD_TEXT_MAX_LENGTH
    },
    showDataSource: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      relatedCodeTemplate:{
        aliasId: '',
        aliasPath: '',
        aliasFieldName:'',
        aliasName:'',
      }
    };
  },
  computed: {
        // 标题内容展示最大数量
    TitleShowMaxLengthMax() {
      return this.formTitleMaxLength || config.FIELD_NAME_LENGTH_MAX;
    },
    /**
     * @description: 选项配置类型
     * @param {*} 0:自定义
     */
    dataSourceType() {
      let setting = this.field.setting || {};
      return setting.dataSourceType || 0;
    },
    dataSourceTypeOptions() {
      return [
        {
          label: i18n.t('common.base.custom'),
          value: 0,
          show: true,
        },
        {
          label: i18n.t('common.form.type.jsCodeBlock'),
          value: 3,
          show: true,
        }
      ].filter(menu => menu.show);
    },
    defaultValueConfig() {
      return this.field.setting.defaultValueConfig || {}
    },
    /** 
    * @description 不允许修改
    * 必填时且无默认值时不可勾选
    */
    modifyDefaultValueDisabled() {
      return !this.field.defaultValue;
    },
    /** 多语言灰度*/
    isOpenMultiLanguage() {
      return getOpenMultiLanguage() || false;
    },
    /** 代码块配置项*/
    codeOptions() {
      let sourceFields = this.fields
      if (isInSubForm(this.field)) {
        const parentFields = this.fields.find(field => field.fieldName === this.field.parentFieldName);
        sourceFields = parentFields?.subFormFieldList || [];
      }
      const codeField = sourceFields.filter(f=> f.formType == 'jsCodeBlock' );
      const codeOptions = [];

      codeField.map(f =>{
        const { resultAliasPath = [] } = f.setting?.codeBlockConfig || {};
        codeOptions.push(...(resultAliasPath.filter(item=> item.aliasName)));
      });
      return codeOptions;
    },
  },
  mounted(){
    this.relatedCodeTemplate = cloneDeep( this.field.setting?.relatedCodeTemplate || this.relatedCodeTemplate);
    // 无匹配代码块配置项数据
    if(!this.codeOptions.some(f=>f.aliasPath == this.relatedCodeTemplate.aliasPath)){
      this.relatedCodeTemplate.aliasPath = '';
    }
  },
  methods: {
    handleInput(e) {
      let value = e.target.value;

      if(this.field.formType === 'currency' && this.type === 'number') {
        value = validateCurrencyNumber(value, this) + '';
      } else {
        if(value.length > this.maxLength) {
          value = value.slice(0, this.maxLength);
        }
      }

      this.update(value, 'defaultValue');
    },
    save(data){
      // 默认字体数据回填
      if(this.field.defaultValue !== data[locales.locale]){
        this.field.defaultValue = data[locales.locale]
      }
      this.update(data, 'defaultValueLanguage');
    },
    update(value, prop, isSetting = false) {
      this.$emit('input', value, prop, isSetting);
    },
    updateDataSourceType(dataSourceType) {
      this.update(dataSourceType, 'dataSourceType', true);

      // 重置默认值
      this.update('', 'defaultValue');
      this.update({}, 'filter', true);
      this.update({}, 'relatedCodeTemplate', true);
    },
    /* 更新代码块关联字段 */
    updateRelatedCode() {
      const codeOptions = cloneDeep(this.codeOptions);
      const relatedCodeTemplate = codeOptions.find(f=> f.aliasPath == this.relatedCodeTemplate.aliasPath);

      this.relatedCodeTemplate = relatedCodeTemplate;
      // 更新关联表单数据
      this.update(relatedCodeTemplate, 'relatedCodeTemplate', true);

      this.$emit('update');
    },
  },
  watch: {
    modifyDefaultValueDisabled(newValue) {
      if (newValue) {
        this.defaultValueConfig.isNotModify = 0;
        this.update(this.defaultValueConfig, 'defaultValueConfig', true);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-default-value-setting {
    .default-value__input{
    display: flex;
    align-items: center;
    p{
      display: flex;
      justify-content: center;
      align-items: center;
      flex-shrink: 0;
      width: 32px;
      height: 32px;
      background: #F5F8FA;
      border-radius: 4px;
      border: 1px solid #CBD6E2;
      text-align: center;
      margin-bottom: 0;
      margin-left: 8px;
      cursor: pointer;
      .iconfont{
        font-size: 18px;
        color: #595959;
        &:hover{
          color: $color-primary;
        }
      }
    }
  }
  .form-item-title {
    margin-bottom: 0;
  }

  .form-item-box {
    margin-top: 8px;
    input {
      width: 100%;
      margin-top: 8px;
    }
  }
  .select-language-wrap {
    display: flex;
    align-items: flex-end;
  }

  .data-source-type {
    width: 100%;
    margin-bottom: 8px;
  }
    .form-code-setting {
    width: 100%;
  }
}

:deep(.form-code-setting__popover){
  width: 100%;
}
</style>